package com.yuanqi.controller;

import com.yuanqi.common.Result;
import com.yuanqi.pojo.Unit;
import com.yuanqi.service.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 单位管理控制器
 */
@RestController
@RequestMapping("/api/unit")
public class UnitController {

    @Autowired
    private UnitService unitService;

    /**
     * 获取单位列表
     */
    @GetMapping("/list")
    public Result<List<Unit>> getUnitList() {
        List<Unit> units = unitService.list();
        return Result.success(units);
    }

    /**
     * 分页查询单位
     */
    @GetMapping("/page")
    public Result<Object> getUnitPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String unitName) {
        
        return unitService.getUnitPage(current, size, unitName);
    }

    /**
     * 获取单位详情
     */
    @GetMapping("/{id}")
    public Result<Unit> getUnitDetail(@PathVariable Long id) {
        Unit unit = unitService.getById(id);
        return Result.success(unit);
    }

    /**
     * 新增单位
     */
    @PostMapping
    public Result<Boolean> createUnit(@RequestBody Unit unit) {
        boolean ok = unitService.save(unit);
        return Result.success(ok);
    }

    /**
     * 更新单位
     */
    @PutMapping("/{id}")
    public Result<Boolean> updateUnit(@PathVariable Long id, @RequestBody Unit unit) {
        unit.setId(id);
        boolean ok = unitService.updateById(unit);
        return Result.success(ok);
    }

    /**
     * 删除单位
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteUnit(@PathVariable Long id) {
        boolean ok = unitService.removeById(id);
        return Result.success(ok);
    }
}
